package dom;

import java.io.File;

import javax.xml.crypto.dsig.Transform;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class TestDom {

	public static void main(String[] args) {

		 TestDom.readXml();
		// TestDom.delXml();
		//	TestDom.updateXml();
		//TestDom.insertXml();
	}



	private static void readXml() {
		File file = new File("./src/student.xml");
		// 得到 DOM 解析器的工厂实例
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = null;
		Document document = null;
		try {
			// 得到DOM解析器
			documentBuilder = factory.newDocumentBuilder();
			// 解析xml文档，得到DOM对象
			document = documentBuilder.parse(file);
			// 获取文档的根节点
			Element rootElement = document.getDocumentElement();
			// 获取根节点中的student节点，返回NodeList集合
			NodeList nodeList = rootElement.getElementsByTagName("student");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element student = (Element) nodeList.item(i);

				String stu_id = student.getAttribute("id");

				// 获取student元素节点中第一个名叫name的元素节点，中的第一个子节点的值。
				String stu_name = student.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
				String age = student.getElementsByTagName("age").item(0).getFirstChild().getNodeValue();
				String sex = student.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue();
				String content = student.getElementsByTagName("content").item(0).getFirstChild().getNodeValue();
				System.out.println(
						"id=" + stu_id + "stu_name=" + stu_name + "age=" + age + "sex=" + sex + "content=" + content);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void delXml() {

		File file = new File("./src/student.xml");

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		Document document = null;
		try {
			builder = factory.newDocumentBuilder();
			document = builder.parse(file);

			Element rootElement = document.getDocumentElement();
			Element parenElement = (Element) rootElement.getElementsByTagName("root").item(0);
			NodeList nodeList = rootElement.getElementsByTagName("student");

			for (int i = 0; i < nodeList.getLength(); i++) {

				Element student = (Element) nodeList.item(i);

				// 移除属性id=3的 student元素节点
				if (student.getAttribute("id").equals("03")) {
					// 要移除某个节点，必须这个节点的父节点的remove方法来移除
					parenElement.removeChild(student);
					break;
				}
			}

			// 重新将Document整个文档对象写回到XML文件中。
			// 这段代码的关键是将文档内容保存在文件中
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();

			// 设置输出格式，以utf-8且缩进格式
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");

			DOMSource source = new DOMSource(document);
			StreamResult streamResult = new StreamResult(file);
			transformer.transform(source, streamResult);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void updateXml() {
		File xmlFile = new File("./src/student.xml");
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = null;
		Document document = null;
		try {
			documentBuilder = builderFactory.newDocumentBuilder();
			document = documentBuilder.parse(xmlFile);

			Element rootElement = document.getDocumentElement();

			NodeList nodeList = rootElement.getElementsByTagName("student");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element student = (Element) nodeList.item(i);
				String stu_id = student.getAttribute("id");

				if (stu_id.equals("02")) {
					// 修改属性id=02的信息
					student.getElementsByTagName("name").item(0).getFirstChild().setNodeValue("被修改后的张三");
					student.getElementsByTagName("sex").item(0).getFirstChild().setNodeValue("女");
				}

			}

			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();

			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

			DOMSource domSource = new DOMSource(document);
			StreamResult result = new StreamResult(xmlFile);
			transformer.transform(domSource, result);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	private static void insertXml() {
			File xmlFile=new File("./src/student.xml");
			DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder=null;
			Document document=null;
			try {
				documentBuilder=builderFactory.newDocumentBuilder();
				document=documentBuilder.parse(xmlFile);
				
				
				Element rootElement=document.getDocumentElement();
				//往root节点下添加节点
				Element parenElment=(Element)rootElement.getElementsByTagName("root").item(0);
				//往studentElment节点下添加节点
				Element studentElment=document.createElement("student");
				
				Element nameElment=document.createElement("name");
				nameElment.setTextContent("王五");
				
				Element ageElement=document.createElement("age");
				ageElement.setTextContent("10");
				
				Element sexElment=document.createElement("sex");
				sexElment.setTextContent("男");
				
				Element contentElement=document.createElement("content");
				contentElement.appendChild(document.createCDATASection("这是CDATA节点中的同容^*&%IO(%$R^U*&P^&RI*YHOf"));
				
				//把节点添加到父节点之后
				parenElment.appendChild(studentElment);
				studentElment.appendChild(nameElment);
				studentElment.appendChild(ageElement);
				studentElment.appendChild(sexElment);
				studentElment.appendChild(contentElement);
				
				
				TransformerFactory transformerFactory=TransformerFactory.newInstance();
				Transformer transformer=transformerFactory.newTransformer();
				
				transformer.setOutputProperty(OutputKeys.INDENT, "yes");
				transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
				
				DOMSource xmlSource=new DOMSource(document);
				StreamResult outputTarget=new StreamResult(xmlFile);
				
				transformer.transform(xmlSource, outputTarget);
				
				
				
			} catch (Exception e) {
			}
			
		
		
	}
	
	
}
